import axios from 'axios'
import type { AxiosResponse } from 'axios'
import { ElMessage } from 'element-plus'

// 创建axios实例
const service = axios.create({
  baseURL: '/api', // API的基础URL
  timeout: 15000 // 请求超时时间
})

// 请求拦截器
service.interceptors.request.use(
  (config) => {
    // 在发送请求之前做些什么
    const token = localStorage.getItem('token')
    if (token) {
      // 设置saToken到请求头，使用统一的tokenName
      config.headers['satoken'] = token
    }
    // 设置请求内容类型
    /*if (config.method?.toLowerCase() === 'post') {
      config.headers['Content-Type'] = 'application/json'
    }*/
    return config
  },
  (error) => {
    // 对请求错误做些什么
    console.error('Request error:', error)
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  (response: AxiosResponse) => {
    const res = response.data

    // 根据后端返回的状态码判断请求是否成功
    if (res.code !== 200) {
      ElMessage({
        message: res.message || 'Error',
        type: 'error',
        duration: 5 * 1000
      })

      // 401: 未登录或token过期
      if (res.code === 401) {
        // 跳转到登录页
        localStorage.removeItem('token')
        window.location.href = '/login'
      }

      return Promise.reject(new Error(res.msg || 'Error'))
    } else {
      return res
    }
  },
  (error) => {
    console.error('Response error:', error)
    ElMessage({
      message: error.message || 'Request failed',
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

// 封装GET请求
export function get<T>(url: string, params?: any): Promise<T> {
  return service.get(url, { params }).then(res => res.data)
}
/*export function download<T>(url: string,params?: any): Promise<T>{
  return request({
    url,
    method: 'get',
    params,
    responseType: "blob"
  })
}*/

// 封装POST请求
export function post<T>(url: string, data?: any): Promise<T> {
  return service.post(url, data).then(res => res.data)
}

// 封装FormData方式的POST请求
export function postFormData<T>(url: string, data?: any): Promise<T> {
  const formData = new FormData()
  if (data) {
    Object.keys(data).forEach(key => {
      if (Array.isArray(data[key])) {
        // 如果是数组，则遍历添加每个元素
        data[key].forEach((item: any) => {
          formData.append(key, item)
        })
      } else {
        formData.append(key, data[key])
      }
    })
  }
  return service.post(url, formData, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  }).then(res => res.data)
}

// 封装PUT请求
export function put<T>(url: string, data?: any): Promise<T> {
  return service.put(url, data).then(res => res.data)
}

// 封装DELETE请求
export function del<T>(url: string, params?: any): Promise<T> {
  return service.delete(url, { params }).then(res => res.data)
}

export default service
